package news

import (
	"net/http"
	"parking-lot-go-admin/controller"
	"parking-lot-go-admin/model"
	"parking-lot-go-admin/model/dingtalk"

	"github.com/gin-gonic/gin"
)

func UpdateNews(c *gin.Context) {

	id := c.PostForm("id")
	classId := c.PostForm("class_id")
	title := c.PostForm("title")
	introduce := c.PostForm("introduce")
	content := c.PostForm("content")
	sort := c.PostForm("sort")
	clicks := c.PostForm("clicks")
	isTop := c.PostForm("is_top")

	//图片判断更新
	randomFileName := ""
	_, err := c.FormFile("fileList[0][raw]")
	if err != http.ErrMissingFile {
		//获取上传文件
		randomFileName, err = controller.GetUploadFile(c, "fileList")
		if err != nil {
			controller.Fail(c, err.Error())
			return
		}
	}

	//更新信息
	update := map[string]interface{}{
		"class_id":  classId,
		"title":     title,
		"introduce": introduce,
		"content":   content,
		"clicks":    clicks,
		"is_top":    isTop,
		"sort":      sort,
	}

	if randomFileName != "" {
		update["image_path"] = randomFileName
	}

	var dingtalkNewsStruct dingtalk.DingtalkNewsStruct
	model.UpdateModelData(
		model.Db,
		dingtalkNewsStruct.TableName(),
		map[string]interface{}{
			"id": id,
		},
		update,
	)

	controller.Success(c, "")
}
